/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
    TreeNode *replaceValueInTree(TreeNode *root)
    {
        vector<pair<TreeNode *, TreeNode *>> layer{{root, nullptr}};
        root->val = 0;
        while (!layer.empty())
        {
            int layerSum = 0;
            vector<pair<TreeNode *, TreeNode *>> nextLayer;

            for (auto &[node, parent] : layer)
            {
                layerSum += node->val;
                if (node->left != nullptr)
                {
                    nextLayer.push_back({node->left, node});
                }
                if (node->right != nullptr)
                {
                    nextLayer.push_back({node->right, node});
                }
            }

            vector<int> newVals;
            for (auto &[node, parent] : layer)
            {
                if (parent == nullptr)
                {
                    continue;
                }
                int brotherSum = 0;
                if (parent->left != nullptr)
                {
                    brotherSum += parent->left->val;
                }
                if (parent->right != nullptr)
                {
                    brotherSum += parent->right->val;
                }
                newVals.push_back(layerSum - brotherSum);
            }
            for (int i = 0; i < newVals.size(); ++i)
            {
                layer[i].first->val = newVals[i];
            }
            layer.swap(nextLayer);
        }
        return root;
    }
};